<template>
	<!-- 
	注意
		<up-picker>本项目使用的uview-plus版本为3.4.97,需要更改框架中的inputPropsInner,否者会报警告
	 -->
	<view class="main-box">
		<!-- 注意，
			如果需要兼容微信小程序，最好通过setRules方法设置rules规则
			up-picker-data没有inputProps属性设置输入框样式，需要自己去组件内加
		 -->
		<!-- 表单 -->
		<up-form :model="form" :borderBottom="true" ref="uFormRef" labelWidth="auto" style="padding: 0 20rpx;
						background-color: #ffffff;">
			<up-form-item @click="toSelectCus" label="客户" prop="customerSeleted"
				:borderBottom="true" required>
				<up-input style="pointer-events: none" readonly v-model="form.customerSeletedName"
					placeholder="" border="none" inputAlign="right" />
				<template #right>
					<up-icon name="arrow-right"></up-icon>
				</template>
			</up-form-item>
			<up-form-item label="销售仓库" prop="salesWarehouseSeleted" :borderBottom="true" required>
				<up-picker-data style="width: 100%;"
					:inputProps="{inputAlign:'right',border:'none'}" labelKey="label"
					valueKey="value" v-model="form.salesWarehouseSeleted"
					v-model:show="warehousePickerShow" :options="warehouseDict"
					:closeOnClickOverlay="true" @close="console.log(111)" hasInput></up-picker-data>
				<template #right>
					<up-icon name="arrow-right"></up-icon>
				</template>
			</up-form-item>
			<!-- 填写更多 -->
			<view v-show="fillMoreShow">
				<up-form-item label="业务员" prop="salespersonSeleted" :borderBottom="true">
					<up-picker-data style="width: 100%;" :inputProps="{
										inputAlign:'right',
										border:'none',
										placeholder:'不填写默认为当前账号'
									}" labelKey="label" valueKey="value" v-model="form.salespersonSeleted" :options="userDict"
						:closeOnClickOverlay="true" hasInput></up-picker-data>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
				</up-form-item>
			</view>
			<view @click="fillMoreShow = !fillMoreShow" style="display: flex;
						 justify-content: center;
						 padding: 30rpx 0;">
				<up-icon labelPos="left" :label="fillMoreShow?'收起更多':'填写更多'"
					:name="fillMoreShow?'arrow-up':'arrow-down'" class="right"></up-icon>
			</view>
		</up-form>

		<!-- 加商品 -->
		<drag-button :isDock="true" :existTabBar="true" :initPaddingBottom="300" text="添加商品"
			@btnClick="toProductPage" style="padding: 20rpx;" />

		<!-- 商品列表 -->
		<view>
			<!-- 表头 -->
			<view style="font-size: 28rpx;
			             font-weight: 300;
			             background-color: #e3e8fb;
			             padding: 8rpx 20rpx;
			             display: flex;">
				<view style="flex:1">商品</view>
				<view style="width:180rpx">销售价</view>
				<view style="width:180rpx;text-align: right;">数量/小计</view>
			</view>
			<!-- 表体 -->
			<view>
				<up-empty v-if="carList.length === 0" mode="data" icon="data"></up-empty>
				<up-swipe-action v-else>
					<up-swipe-action-item v-for="(item,index) in carList" @click="swipeClick"
						:name="index" :options="options">
						<view style="display: flex;position: relative;
										background-color: #ffffff;
										 padding: 20rpx 20rpx 8rpx 20rpx;">
							<view style="flex:1">
								<!-- 商品名称 -->
								<view style="font-size: 24rpx;">
									<text style="color: #3c9cff;
													 padding: 4rpx 16rpx;
													 background-color: #edf0f9;">
										{{index+1}}
									</text>
									<text style="font-weight: bold;
													 font-size: 30rpx;
													 margin-left: 10rpx;">
										{{item.pname}}
									</text>
								</view>
								<!-- 库存 -->
								<view style="font-size: 24rpx;padding: 6rpx 0;">
									<text>{{item.formulatext}}</text>

								</view>
							</view>
							<!-- 销售价 -->
							<view style="width:180rpx;font-weight: bold;font-size: 30rpx;">
								<view style="font-weight: bold;font-size: 30rpx;">
									{{'￥'+ item.unitPrice + '/' + item.selectedUnit}}
								</view>

							</view>
							<!-- 数量/小计 -->
							<view style="width:180rpx;text-align: right;">
								<view style="font-weight: bold;font-size: 30rpx;">
									{{item.quantity}}{{item.selectedUnit}}
								</view>
								<view style="font-size: 24rpx;font-weight: bold;color: #3c9cff;">
									{{'￥' + item.unitPrice*item.quantity}}
								</view>
							</view>
							<view
								style="position: absolute;transform: rotate(20deg);transform-origin: center center;left:200rpx;top:20rpx">
								<up-tag :text="item.selectedBusinessType" plain size="mini"
									type="primary"></up-tag>
							</view>
						</view>
					</up-swipe-action-item>
				</up-swipe-action>
			</view>
		</view>



		<!-- 占位置 -->
		<view :style="{height:BottomHeight+'px'}"></view>
		<view id="bottom-box" style="background-color: #ffffff;
					 position: fixed;
					 bottom: 0;
					 left: 0;
					 width: 100%;
					 z-index: 998;
					 box-sizing: content-box;
					 border-top: 1px solid #dedede;
					 padding-bottom: env(safe-area-inset-bottom);">
			<view style="display: flex;
						 padding: 20rpx 20rpx 0 20rpx;">
				<view style="margin-left: auto;">
					<text>合计：</text>
					<text style="font-size: 48rpx;
								 color:#C06E5D;
								 font-weight: bold;">￥{{getCartTotal}}</text>
				</view>
			</view>
			<view style="padding: 20rpx;">
				<up-button type="primary" @click="submitForm">提交</up-button>
			</view>
		</view>

	</view>
</template>

<script setup>
	import Decimal from 'decimal.js'
	import { ref, reactive, watch, nextTick, computed } from 'vue'
	import { onReady, onLoad } from "@dcloudio/uni-app"
	import { useStore } from "vuex";
	import { timeFrom } from '@/uni_modules/uview-plus';
	const store = useStore();
	const app = getApp()


	// data
	const options = ref([{ // swipe滑动按钮
		text: '删除',
		style: {
			backgroundColor: '#f56c6c'
		}
	}]);
	const BottomHeight = ref(0) // 布局_底部
	const form = ref({ // data_车销订单表单数据
		customerSeleted: null, // 客户
		customerSeletedName: "",
		salesWarehouseSeleted: null, // 销售仓库
		salespersonSeleted: null, // 业务员不填写默认为当前登录人
		discount: 0 // 整单优惠
	})
	const rules = ref({ // 校验规则
		customerSeleted: [{
			required: true,
			type: 'number',
			message: '请选择客户',
			trigger: ['change', 'blur'],
		}],
		salesWarehouseSeleted: [{
			required: true,
			type: 'number',
			message: '请选择仓库',
			trigger: ['change', 'blur'],
		}]
	})
	const warehouseDict = ref([])
	const userDict = ref([])
	const uFormRef = ref(null); // 表单引用
	const fillMoreShow = ref(false); // 开关_填写更多
	const warehousePickerShow = ref(false); // 开关_仓库picker
	const carList = ref([])

	onReady(async () => {
		// 如果需要兼容微信小程序，最好通过setRules方法设置rules规则
		uFormRef.value.setRules(rules.value)
		uni.createSelectorQuery().select('#bottom-box').boundingClientRect(b_data => {
			BottomHeight.value = b_data.height
		}).exec()
	})
	onLoad(async () => {
		const res = await app.globalData.http.get("/warehouse/dict")
		warehouseDict.value = res.data
		const userDictRes = await app.globalData.http.get("/sysUser/dict")
		userDict.value = userDictRes.data
	})

	// 监听 form.number 的变化解决picker第一次选择后不触发form的表单校验的bug
	watch(() => form.value.customerSeleted, (newVal, oldVal) => {
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('customerSeleted');
			}
		}
	});
	watch(() => form.value.salesWarehouseSeleted, (newVal, oldVal) => {
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('salesWarehouseSeleted');
			}
		}
	});


	// 购物车合计
	// const getCartTotal = computed(() => {
	// 	let total = 0;
	// 	carList.value.forEach(item => {
	// 		const xiaoji = item.unitPrice * item.quantity
	// 		total += xiaoji
	// 	});
	// 	return total;
	// })

	const getCartTotal = computed(() => {
		return carList.value.reduce((sum, item) => {
			const subtotal = new Decimal(item.unitPrice).mul(item.quantity)
			return new Decimal(sum).plus(subtotal)
		}, new Decimal(0)).toNumber()
	})

	// swipe滑动点击删除
	const swipeClick = (e) => {
		const index = e.name // 是第几条数据
		const operator = options.value[e.index].text
		if (operator === "删除") {
			carList.value.splice(index, 1)
		}
	}

	// 去选择客户 仓库页
	const toSelectCus = (type) => {
		uni.navigateTo({
			url: '/pages/selectCus'
		})
	}
	// 选择客户
	const setCus = (id, name) => {
		form.value.customerSeleted = id
		form.value.customerSeletedName = name
	}

	// 去选择商品
	const toProductPage = () => {
		if(form.value.salesWarehouseSeleted==null) {
			uni.showModal({
				showCancel: false,
				title: '请先选择仓库，再去添加商品!'
			})
			return 
		}
		uni.navigateTo({
			url: `/pageCarSale/addProduct?id=${form.value.salesWarehouseSeleted}`
		})
	}

	// 添加商品到购物车
	const addProduct = (product) => {
		carList.value.push(product)
	}

	// 提交方法
	const submitForm = () => {
		uFormRef.value.validate().then(async (valid) => {
			if (valid) {
				if (carList.value.length === 0) {
					app.globalData.modal.msgError("请添加商品")
					return
				}
				const insertRecords = carList.value.map(item => ({
					pid: item.pid,
					saletype: item.selectedBusinessType,
					unit: item.selectedUnit,
					number: item.quantity,
					unitprice: item.unitPrice
				}))
				const param = {
					cusid: form.value.customerSeleted,
					whid: form.value.salesWarehouseSeleted,
					owner: form.value.salespersonSeleted ? form.value
						.salespersonSeleted : store.state.user.userId,
					type: "车销订单",
					list: insertRecords
				}
				const res = await app.globalData.http.post("/sale/create", param)
				if (res.code == 200) {
					/*
					就算不加上判断，当code不为200的时候，以下代码也不会执行，会进入异常。
					稳妥起见，还是加上吧，不能信任后台。
					*/
					uni.showModal({
						showCancel: false,
						title: `创建订单成功!`,
						success: function(res) {
							if (res.confirm) {
								let pages = getCurrentPages()
								let prevPage = pages[pages.length -
									2];
								//刷新订单页面
								prevPage._.exposed.initData()
								//刷新今日统计
								store.dispatch("GetTodayStat")
								uni.navigateBack()
							}
						}
					})
				}
			} else {
				console.log(valid)
			}
		}).catch(() => {
			// 处理验证错误  
		});
	}

	// 一定要放在最后，不然会报错
	defineExpose({
		addProduct,
		setCus
	})
</script>

<style lang="scss" scoped>

</style>